<template>
<!-- 关注模块 -->
   <van-button
      v-if="isFollowed"
      class="follow-btn"
      round
      size="small"
      :loading="loading"
      @click="onFollow"
      >已关注</van-button
   >
   <van-button
      v-else
      class="follow-btn"
      type="info"
      color="#3296fa"
      round
      size="small"
      icon="plus"
      :loading="loading"
      @click="onFollow"
      >关注</van-button
   >
</template>

<script>
import { addFollow, deleteFollow } from '@/api/user'
export default {
   data() {
      return {
         loading: false
      }
   },
   // 自定义 v-model 的数据名称
   model: {
      // 默认是 value
      prop: 'isFollowed',
      // 默认事件是 input
      event: 'update-is_followed'
   },
   // props: {
   //    value: {
   //       type: Boolean,
   //       required: true
   //    }
   // },
   props: {
      isFollowed: {
         type: Boolean,
         required: true
      },
      userId: {
         type: [Number, String, Object],
         required: true
      }
   },
   methods: {
      async onFollow() {
         // 展示关注按钮的 loading 状态
         this.loading = true
         try {
            if (this.isFollowed) {
               // 已关注，取消关注
               await deleteFollow(this.userId)
               // console.log(data)
               // this.article.is_followed = false
            } else {
               // 未关注，添加关注
               await addFollow(this.userId)
               // console.log(data)
               // this.article.is_followed = true
            }
            // 更新视图状态
            // this.isFollowed = !this.isFollowed
            this.$emit(
               'update-is_followed',
               !this.isFollowed
            )
            // this.$emit('input', !this.value)
            // this.$emit('update:is-followed', !this.value)
         } catch (err) {
            let message = '操作失败，请重试'
            if (
               err.response &&
               err.response.status === 400
            ) {
               message = '你不能关注你自己'
            }
            this.$toast(message)
         }
         // 关闭关注按钮的 loading 状态
         this.loading = false
      }
   }
}
</script>

<style lang="less" scoped></style>
